from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import Alignment


wb = load_workbook('example.xlsx')
ws = wb.active
with open('ocr_results.txt', 'r', encoding='utf-8') as f:
    content = f.readlines()
print(content[1])

class result:
    def __init__(self):
        self.tech = None
        self.speed = None
        self.player1 = None  # 比分框上方球员
        self.game1 = None
        self.point1 = None
        self.player2 = None  # 比分框下方球员
        self.game2 = None
        self.point2 = None
        self.color = None

result = result()
result.player1 = 'player1'
result.player2 = 'player2'
ws['A1'] = result.player1+'分数'
ws['B1'] = result.player2+'分数'
ws['C1'] = result.player1
ws['G1'] = result.player2
last_color = None
last_speed = None
rd = 0
end = False
for l in content:
    line = l.split(' ')
    i = 0
    for text in line:
        i += 1
        if text == '发球' or text == '正手' or text == '反手' or text == '落网' :
            result.tech = text
            for j in range(len(line)):
                if line[j] == 'km/h':
                    result.speed = line[j-1]
                    if result.tech == '落网':
                        result.speed = 0
            result.game1 = line[1]
            result.point1 = line[2]
            result.game2 = line[3]
            result.point2 = line[4]
            result.color = None
            if line[-1] == 'r\n':
                result.color = '红'
            if line[-1] == 'g\n':
                result.color = '绿'
            if line[-1] == 'y\n':
                result.color = '黄'
            if result.color != None:
                rd += 1
                print(result.tech, result.speed, result.player1, result.game1, result.point1,
                  result.player2, result.game2, result.point2, result.color)
                if rd%2 == 1:
                    ws[f"A{int(rd/2+3)}"] = result.game1 + ' - ' + result.point1
                    ws[f"B{int(rd/2+3)}"] = result.game2 + ' - ' + result.point2
                    ws[f"D{int(rd/2+3)}"] = result.tech
                    ws[f"F{int(rd/2+3)}"] = str(result.speed) +' km/h'
                    ws[f"L{int(rd/2+3)}"] = int(rd/2)+1
                    if result.tech == '落网':
                        ws[f"K{int(rd/2+3)}"] = result.player2
                if rd % 2 == 0:
                    ws[f"H{int(rd/2+2)}"] = result.tech
                    ws[f"J{int(rd/2+2)}"] = str(result.speed) + ' km/h'
                    if result.tech == '落网':
                        ws[f"K{int(rd/2+2)}"] = result.player1
            last_color = result.color
            last_speed = result.speed

# 设置所有单元格的对齐方式
for row in ws:
    for cell in row:
        cell.alignment = Alignment(horizontal='center', vertical='center', wrapText=True)
wb.save('example.xlsx')